package net.hmr_radio.hmrbot.controller.task;

import java.util.Date;
import java.util.List;

import net.hmr_radio.hmrbot.model.Bot;
import net.hmr_radio.hmrbot.service.BotService;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

public class RunBotController extends Controller {

    private Log log = LogFactory.getLog(RunBotController.class);

    private BotService botService = new BotService();

    @Override
    public Navigation run() throws Exception {
        log.info("ボットがしゃべるよー");
        try {

            List<Bot> bots = botService.getRunBots();
            log.info("今回しゃべるボットは" + bots.size() + "体だよー");

            for (Bot bot : bots) {
                try {
                    tweet(bot);
                } catch (TwitterException e) {
                    log.error("ボット " + bot.getName() + "君 エラリました", e);
                }

                bot.setLastRun(new Date());
                botService.save(bot);
            }
            return null;

        } finally {
            log.info("ボットがしゃべったよー");
        }
    }

    private void tweet(Bot bot) throws TwitterException {
        log.info("ボット " + bot.getName() + "君 スタート");
        try {

            Twitter twitter = bot.createTwitterOrNull();
            if (twitter == null) {
                return;
            }

            // Mentionに返信
            ResponseList<Status> mentions = twitter.getMentions();
            for (Status status : mentions) {
                if (botService.isReplied(bot.getTwitterId(), status.getId())) {
                    continue;
                }
            }

        } finally {
            log.info("ボット " + bot.getName() + "君 おわり");
        }
    }

    @Override
    protected Navigation handleError(Throwable error) throws Throwable {
        log.error("エラリました", error);
        return null;
    }
}
